package com.five.years.common.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    private static final MediaType MEDIA_JSON = MediaType.parse("application/json; charset=utf-8");

    private static final MediaType MEDIA_FORM = MediaType.parse("application/x-www-form-urlencoded;");

    private static final OkHttpClient okHttpClient = new OkHttpClient();

    public static OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    public static JSONObject getURLContentByPost(String url, String json) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            RequestBody body = RequestBody.create(MEDIA_JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();

            return JSONObject.parseObject(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String postData(String url, String json) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();
            if (StringUtils.isBlank(json)) {
                json = "name";
            }
            RequestBody  body = RequestBody.create(MEDIA_JSON, json);
            Request request = new Request.Builder().addHeader("key", "fms9h5FmbFAHtS2R")
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] postByteData(String url, String json) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            RequestBody body = RequestBody.create(MEDIA_JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();

            return response.body().bytes();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getData(String url,String key) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            Request request = new Request.Builder().addHeader("key", key)
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getURLContent(String url) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();

            return JSONObject.parseObject(response.body().string());
        } catch (Exception e) {
            logger.error("getURLContent {} failed:{}", url, e.getMessage());
        }
        return null;
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }

    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static JSONObject getBarcodeContent(String url, String cookie, String referer, String barCodeNum) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            Request request = new Request.Builder()
                    .addHeader("Cookie", "ASP.NET_SessionId=" + cookie)
                    .addHeader("Referer", referer + barCodeNum)
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            return JSONObject.parseObject(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getQueryData(String getUrl) {
        try {
            URL url = new URL(getUrl);// 字符串转成请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 响应结果为输入流
            String line;
            StringBuilder sb = new StringBuilder();// 输出的结果
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败 :" + e.getMessage());
        }
        return null;
    }

    public static String postDataAddHeader(String url, String json, String key) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            RequestBody body;
            if (StringUtils.isNull(json)) {
                body = RequestBody.create(null, new byte[0]);
            } else {
                body = RequestBody.create(MEDIA_JSON, json);
            }
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("key", key)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postDataAddHeaderXForm(String url, String json, String key) {
        try {
            OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
            mBuilder.sslSocketFactory(createSSLSocketFactory());
            mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
            OkHttpClient client = mBuilder.build();

            RequestBody body;
            if (StringUtils.isNull(json)) {
                body = RequestBody.create(null, new byte[0]);
            } else {
                body = RequestBody.create(MEDIA_FORM, json);
            }
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("key", key)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
